# _*_coding: utf-8_*_
from django.shortcuts import render
from datetime import datetime
import datetime
from django.utils import timezone
from django.views.generic.base import View
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.db.models.query_utils import Q
from django.contrib.auth.hashers import make_password
# from django.http import HttpResponseRedirect
from .forms import LoginForm, RegisterForm, ForgetPwdForm, UpdatepwdForm
from .models import UserProfile, EmailVerifyRecord
from eduOnline.settings import EXPIRATION_TIMEOUT
from utils.email import send_an_email
# Create your views here.


# 用户名使用username或email都可以登录 settings要配置AUTHENTICATION_BACKENDS
class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # noinspection PyBroadException
        try:
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


# 登出
class LogoutView(View):
    def get(self, request):
        logout(request)
        return render(request, 'index.html')
        # return HttpResponseRedirect(reverse("index"))


# 激活账户
class ActiveView(View):
    def get(self, request, email_code):
        records = EmailVerifyRecord.objects.filter(code=email_code)
        if records:
            for record in records:
                if record.send_time + datetime.timedelta(minutes=int(EXPIRATION_TIMEOUT)) > timezone.now():
                    user = UserProfile.objects.get(email=records.email)
                    user.is_active = True
                    user.save()
                    return render(request, 'login.html')
        return render(request, 'message.html', {'msg': '链接已过期，请重试'})


# 更新密码 找回密码
class UpdatePwdView(View):
    def post(self, request):
        updatepwd_form = UpdatepwdForm(request.POST)
        email = request.POST.get('email')
        if updatepwd_form.is_valid():
            password = request.POST.get('password')
            password2 = request.POST.get('password2')
            if password == password2:
                user = UserProfile.objects.get(email=email)
                user.password = make_password(password)
                user.save()
                return render(request, 'login.html')
        return render(request, 'password_reset.html', {'updatepwd_form': updatepwd_form, 'email': email})


# 忘记密码，从邮件链接跳转来
class ResetView(View):
    def get(self, request, email_code):
        records = EmailVerifyRecord.objects.filter(code=email_code)
        if records:
            for record in records:
                if record.send_time + datetime.timedelta(minutes=int(EXPIRATION_TIMEOUT)) > timezone.now():
                    return render(request, 'password_reset.html', {'email': record.email})
        return render(request, 'message.html', {'msg': '链接已过期，请重试'})


# 忘记密码, 申请发邮件
class ForgetPwdView(View):
    def get(self, request):
        forgetpwd_form = ForgetPwdForm()
        return render(request, 'forgetpwd.html', {'forgetpwd_form': forgetpwd_form})

    def post(self, request):
        forgetpwd_form = ForgetPwdForm(request.POST)
        if forgetpwd_form.is_valid():
            email = request.POST.get('email')
            send_an_email(email, 'forget')
            return render(request, 'message.html', {'msg': '邮件已发送'})
        return render(request, 'forgetpwd.html', {'forgetpwd_form': forgetpwd_form})


# 首页
class IndexView(View):
    def get(self, request):
        return render(request, 'index.html')


# 注册
class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            email = request.POST.get('email')
            user_set = UserProfile.objects.filter(email=email)
            # 用户名已存在
            if user_set:
                if user_set[0].is_active:  # 已激活
                    return render(request, 'register.html', {'register_form': register_form, 'msg': '用户已存在！'})
                else:  # 未激活
                    send_an_email(email)
                    return render(request, 'message.html', {'msg': '用户已注册，尚未激活，已再次发送激活链接到{},请及时点击链接验证邮箱'.format(email)})

            # 用户名不存在
            password = request.POST.get('password')
            # 保存到数据库
            user = UserProfile()
            user.username = email
            user.email = email
            user.password = make_password(password)
            user.is_active = False
            user.save()
            # 发送邮箱
            send_an_email(email)
            return render(request, 'message.html', {'msg': '我们已经向您的邮箱发送了邮件，为保证您的账号安全，请及时点击链接验证邮箱'})
        return render(request, 'register.html', {'register_form': register_form})


# 登录
class LoginView(View):
    def get(self, request):
        login_form = LoginForm()
        return render(request, 'login.html', {'login_form': login_form})

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            username = request.POST.get('username')
            password = request.POST.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    # return HttpResponseRedirect(reversed('index'))
                    return render(request, 'index.html')
                else:
                    return render(request, 'login.html', {'msg': '用户未激活', 'username': username, 'password':password})
            else:
                return render(request, 'login.html', {'msg': '用户名或密码错误', 'username': username, 'password':password})
        return render(request, 'login.html', {'login_form': login_form})
